<?php 

require_once('../include/GeneralTop.php');
require('../include/class/db.php');
require('../include/class/pagination.php');
require('../include/lib/phpmailer/class.phpmailer-lite.php');

if (!$content_admin) {
	die('<div style="text-align:center">Permission denied...</div>');
}

$db = new db;

if ((isset($_GET['action'])) && $_GET['action'] == "resend") {
    //set failed to 0, then we can calculate it again
    $insert_id = $_GET['id'];
    $sql = "update newsletter_log set failed=0 where id=$insert_id";
    $db->query($sql);
    
    $sql = "select newsletter_content, batch from newsletter_log where id=$insert_id";
	$res = $db->query($sql);
	$row = $db->fetch($res);
	$batch_name_failed = $row['batch'].'_failed';
	$filename = NEWSLETTER_LOG_MAIL_ADDRESS_PATH.'/'.$row['batch'].'_failed';
	$content = unserialize(file_get_contents($filename));
	$email_count = count($content);
	@unlink($filename);

	//echo '<pre>';
	//print_r($content);
	//echo '</pre>';
	try {
		$mail = new PHPMailerLite(true); //New instance, with exceptions enabled
	
		//$body             = file_get_contents('contents.html');
	
		$mail->AddReplyTo(ADMIN_MAIL_ADDRESS, ADMIN_MAIL_NAME);
	
		$mail->SetFrom(ADMIN_MAIL_ADDRESS, ADMIN_MAIL_NAME);
	
		$to = $content;
		echo "Start sending....<br>";
		foreach($to as $_key => $_value) {
			//print_r($_value);
			$mail->AddAddress($_value['email'], $_value['name']);		
	  
			$mail->IsMail();
			$mail->CharSet = "utf-8";
		  
			$mail->Subject  = $_POST['title'];
		
			$mail->AltBody    = $_POST['title']; // optional, comment out and test
			$mail->WordWrap   = 80; // set word wrap

			$body = $_value['content'];
			//echo $body.'<br>';
			
			if(isset($_value['token']) && 'no' != $_value['token']) {
				$unsubscribe_address = MAIL_UNSUBSCRIBE_ADDRESS.'?token='.$_value['token'];					
				$body = stripslashes($row['newsletter_content']);
				$body = str_replace(array('[unsubsribe_link]', '[/unsubsribe_link]'), 
									array('<a href="'.$unsubscribe_address.'" target="_BLANK">', '</a>'), 
									$body);
				//echo $body.'<br>';
			}
			else {
				$body = str_replace(array('[unsubsribe_link]', '[/unsubsribe_link]'), 
									array('<span style="display:none">', '</span>'), 
									$body);
			}
			$body = preg_replace('/\\\\/','', $body); //Strip backslashes
			
			$mail->MsgHTML($body);
		
			$mail->IsHTML(true); // send as HTML
			
			$mail->Send();

			$mail->ClearAddresses();
			$mail->ClearAttachments();
		}
		
		$sel_fail = "select failed from newsletter_log where id=$insert_id";
		$sel_fail_res = $db->query($sel_fail);
		$sel_fail_row = $db->fetch($sel_fail_res);
		$fail = $sel_fail_row['failed'];
		$suc = $email_count - $fail;
		echo "Done...<br>
				 $email_count in all, <font color='green'>$suc</font> succeed, <font color='red'>$fail</font> failed.<br><br>";
		
		$end = "update newsletter_log set end_time='".date("Y-m-d H:i:s")."', status=2 where id=$insert_id";
		$db->query($end);
	} catch (phpmailerException $e) {
		echo $e->errorMessage();
		echo "<font color='red'>Error occured...</font><br><br>";
	}			
	$end = "update newsletter_log set end_time='".date("Y-m-d H:i:s")."', status=0 where id=$insert_id";
	$db->query($end);
	
	echo "Sending newsletter process finished.<br>
		<input type='button' value=' back ' onclick='window.location.href=\"NewsletterLog.php\"'>";
	exit();
}

include('AdminPanel.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="../Felix_css.css" rel="stylesheet" type="text/css" />
<title>Newsletter log</title>
</head>

<body>
<table width="60%" border="0" align="center" cellpadding="5" cellspacing="0" class="table_border_grey" style="margin-top:10px;">
  <tr>
    <td colspan="8">
	  <form action="<?php echo $_SERVER['PHP_SELF']?>" method="GET">
	  Search sent newsletters： <input type="text" name="kw" size="20">
	  <input type="submit" name="submit" id="submit" value=" Search title ">
	  </form>
	</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>Title</td>
    <td>Batch</td>
    <td>Total</td>
    <td>Failed</td>
    <td>Status</td>
    <td>Start time</td>
    <td>End time</td>
  </tr>
    <?php
    if(isset($_GET['submit']) && $_GET['kw'] != '') {
		$sql = "SELECT * FROM newsletter_log where newsletter_title like '%".$_GET['kw']."%' ORDER BY id DESC";
	}
	else {
    	$sql = "SELECT * FROM newsletter_log ORDER BY id DESC";
	}
	$res = $db->query($sql);
	$num = $db->num($res);
	if($num > 0) {
		$pagination = new Pagination($num, PAGICATION_RECORD_COUNT_NEWS, $_GET['page'], PAGINATION_DELTA);
		$sql = $sql." limit ".$pagination->begin.",".$pagination->end;
		$res = $db->query($sql);
		while($row = $db->fetch($res)) {
    ?>
    <tr>
      <td>
        <label>
          <input type="button" name="button" id="button" value="Send failed again" onclick="if(confirm('Are you sure to send again?')){window.location.href='<?php echo $_SERVER['PHP_SELF']?>?id=<?php echo $row['id'] ?>&action=resend'}"/>
        </label>
      </td>
      <td><a href="ViewFailed.php?id=<?php echo $row['id'] ?>"><?php echo $row['newsletter_title'] ?></a></td>
      <td><?php echo $row['batch'] ?></td>
      <td><?php echo $row['total'] ?></td>
      <td><?php echo $row['failed'] ?></td>
      <td><?php echo getNewsletterStatus($row['status']) ?></td>
      <td><?php echo $row['start_time'] ?></td>
      <td><?php echo $row['end_time'] ?></td>
    </tr>
    <?php
		}
	}
	?>
	<tr>
    <td colspan="8">
	    <?php
		if($num > PAGICATION_RECORD_COUNT_NEWS) {
			echo $pagination->paginationString;
		}
		?>
	</td>
  </tr>
</table>
<br />
</body>
</html>